<script setup>
import { Cartesian3, CesiumTerrainProvider, HeadingPitchRoll, ImageryLayer, Matrix3, Matrix4, Quaternion, Terrain, Transforms, UrlTemplateImageryProvider, Viewer } from 'cesium';
import { ref, onMounted } from 'vue';

const viewRef = ref();

onMounted(() => {
    const viewer = new Viewer(viewRef.value, {
        animation: false, // 是否显示动画控件
        shouldAnimate: true, // 自动播放动画
        homeButton: false, // 是否显示Home按钮
        fullscreenButton: false, // 是否显示全屏按钮
        baseLayerPicker: false, // 是否显示图层选择控件
        geocoder: false, // 是否显示地名查找控件
        timeline: false, // 是否显示时间线控件
        sceneModePicker: false, // 是否显示投影方式控件
        navigationHelpButton: false, // 是否显示帮助信息控件
        infoBox: false, // 是否显示点击要素之后显示的信息
        requestRenderMode: true, // 启用请求渲染模式
        scene3DOnly: true, // 每个几何实例将只能以3D渲染以节省GPU内存
        sceneMode: 3, // 初始场景模式 1 2D模式 2 2D循环模式 3 3D模式  Cesium.SceneMode
        contextOptions: {
            webgl: { preserveDrawingBuffer: true },// 允许预览，导出图片不会黑屏
        },
        baseLayer: new ImageryLayer(new UrlTemplateImageryProvider({
            url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
            maximumLevel: 18,
        })),
        terrain: new Terrain(CesiumTerrainProvider.fromUrl('http://data.mars3d.cn/terrain')),
    });

    const position = Cartesian3.fromDegrees(102.59876938457637, 30.273206076124293, 3279.875152702345);
    const planeNormal = Cartesian3.fromElements(-0.08230699700986187, 0.9945473568970801, 0.06403993388699498);

    const localMatrix = Transforms.headingPitchRollToFixedFrame(position, HeadingPitchRoll.fromDegrees(90, 0, 0));

    const direction = new Cartesian3(localMatrix[Matrix4.COLUMN1ROW0], localMatrix[Matrix4.COLUMN1ROW1], localMatrix[Matrix4.COLUMN1ROW2]);

    const xAxis = Cartesian3.normalize(Cartesian3.cross(direction, planeNormal, new Cartesian3()), new Cartesian3());
    const yAxis = Cartesian3.normalize(Cartesian3.cross(planeNormal, xAxis, new Cartesian3()), new Cartesian3());

    const computedMatrix = Matrix4.fromRotationTranslation(new Matrix3(
        xAxis.x, yAxis.x, planeNormal.x,
        xAxis.y, yAxis.y, planeNormal.y,
        xAxis.z, yAxis.z, planeNormal.z
    ), position);

    const model = viewer.entities.add({
        position: Matrix4.getTranslation(computedMatrix, new Cartesian3()),
        orientation: Quaternion.fromRotationMatrix(Matrix4.getRotation(localMatrix, new Matrix3())),
        model: { uri: '/models/loon.gltf' },
    });

    viewer.flyTo(model);
});
</script>

<template>
    <div class="w-screen h-screen overflow-hidden" ref="viewRef"></div>
</template>
